package de.jmda.home.ui.vaadin.userguide;


import com.google.common.eventbus.EventBus;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.shared.MouseEventDetails.MouseButton;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalLayout;

import de.jmda.common.ui.web.vaadin.service.DefaultSessionContext;
import de.jmda.home.ui.vaadin.userguide.UserGuideDisplay.UserGuideChapter;

@SuppressWarnings("serial")
public class UserGuideTree implements ItemClickListener
{
	private Tree tree;
	
	private EventBus eventBus = DefaultSessionContext.get().getEventBus();

	public UserGuideTree(VerticalLayout verticalLayout)
	{
		initTree();

		verticalLayout.addComponent(tree);
	}

	@Override
  public void itemClick(ItemClickEvent event)
  {
		if (event.getButton() == MouseButton.LEFT)
		{
			Object itemId = event.getItemId();
			
			if (itemId instanceof UserGuideChapter)
			{
				eventBus.post(
						new UserGuideChapterDisplayRequest((UserGuideChapter) itemId));
			}
		}
  }

	private void initTree()
  {
		tree = new Tree();
		populateTree(UserGuideChapter.FIRST);
		tree.addItemClickListener(this);
  }

	private void populateTree(UserGuideChapter userGuideChapter)
  {
		tree.addItem(userGuideChapter);
		
		if (userGuideChapter.getParent() != null)
		{
			tree.setParent(userGuideChapter, userGuideChapter.getParent());
		}
		
		if (userGuideChapter.getChildren().length == 0)
		{
			tree.setChildrenAllowed(userGuideChapter, false);
		}
		else
		{
			for (UserGuideChapter child : userGuideChapter.getChildren())
			{
				populateTree(child);
			}
		}
		
		if (userGuideChapter.getNext() != null)
		{
			populateTree(userGuideChapter.getNext());
		}
  }
}